package cn.devhost;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * @author shenguangyang
 */
@Slf4j
@Data
@ConfigurationProperties(prefix = "config")
public class ServerProperties {
    /**
     * 网卡: 可以是有线网卡或者无线网卡
     */
    private List<String> networkInterfaces = new ArrayList<>();

    /**
     * 邮件接收者
     */
    private String mailReceiveUser;

    @PostConstruct
    public void init() throws Exception {
        // 初始化本地 resolv 避免自己搭建dns并在resolv中指定, 那在启动时候，
        // 如果服务器ip没有设置静态的, 那么ip很可能发生变化导致有问题
        List<NetworkInfo> netWorkInfos = NetworkUtils.getNetWorkInfo(this.networkInterfaces);
        String resolvFileName = "resolv.conf";
        String resolvPath = "/etc/" + resolvFileName;
        String resolvContent = "nameserver %s";

        NetworkInfo networkInfo = netWorkInfos.stream().filter(e -> StrUtil.isNotEmpty(e.getIp())).findFirst().orElse(null);
        if (networkInfo == null) {
            log.info("获取网卡信息失败, 无法更新本地 {}", resolvPath);
            return;
        }
        resolvContent = String.format(resolvContent, networkInfo.getIp());
        FileUtil.cleanEmpty(new File(resolvPath));
        FileUtil.writeUtf8String(resolvContent, resolvPath);
        log.info("更新本地 {} 文件成功, content: {}", resolvPath, resolvContent);
    }
}
